import React, { useState, useMemo, useEffect } from 'react';
import { ColView, filter_list, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, no_del, trim_data, KFile, HandView, BtTxt,
    Title, cline, obj_int, InfoDlg, uJob, obj_str, PanelFind, Btn, is_empty, loc } from 'sui';
import { face_list } from 'test/base/cmd';
import { get_col, load_ng, load_tech, get_ck, fix_col, load_stuff } from 'test/base/cmd';
import { load_col, load_supply } from '../../stock/base/cmd';
import { useAccess } from 'cache';

const BaseView = ({ mod, submod, title, acc }) => {
    const [open_info, openInfo] = useState(false);
    const [tech, setTech] = useState();
    const [supply, setSupply] = useState();
    const [stuff, setStuff] = useState();
    const [ng, setNg] = useState();
    const [map_stuff, mapStuff] = useState();
    const [map_supply, mapSupply] = useState();
    const [map_ng, mapNg] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const [no_acc] = useAccess();
    const umd = useCmd(`file/list/${mod}`, null, null, "tech");

    useEffect(() => {
        load_col(mod, setCol);
        load_supply(submod, setSupply, mapSupply);
        load_stuff(setStuff, mapStuff);
        load_tech(setTech);
        load_ng(setNg, mapNg, mod);
    }, [mod, submod]);

    const getRow = useMemo(() => {
        const lst = filter_list(["sn"], col);
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter, col]);

    const hreturn = () => {
        load_col(mod, setCol);
        umd.hreturn();
    };

    const pact = {
        "back": v => {
            const order = obj_str(v, "order");
            if (!order) {
                alert(loc("l_580"));
                return;
            }

            if (no_del(loc("l_577"))) {
                return;
            }

            umd.startWait();

            const cmd = {
                line: cline(),
                k: order,
                sn: obj_str(v, "sn"),
                ngson: obj_str(v, "ngson"),
                path: mod,
                num: obj_int(v, "num"),
            };

            uJob(null, "sale/toback", cmd,
                r => {
                    umd.endWait();
                    openInfo(true);
                },
                e => umd.setErr());
        }
    };

    const act = {
        "edit": (v, h) => umd.update(`file/md/${mod}`, {v: v, sn: v["sn"]}, h),
    };

    if (umd.isFin("col")) {
        const list = [
            {sn: mod, name: title, fix: fix_col()},
        ];

        return <ColView hreturn={hreturn} title={title} subtitle={loc("l_221")} list={list} cur={mod}/>;
    }

    const hDel = (d) => {
        if (no_del()) {
            return;
        }

        umd.update(`file/rm/${mod}`, {"sn": obj_str(d, "sn")});
    };

    const hCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const ret = [];

        col.forEach(d => {
            if (d.sn === "sn") {
                d.ctp = "auto";
            } else if (d.sn === "supply") {
                d.ctp = "list";
                d.ctl = supply;
            } else if (d.sn === "tech") {
                d.ctp = "list";
                d.ctl = tech;
            } else if (d.sn === "face") {
                d.ctp = "list";
                d.ctl = face_list();
            } else if (d.sn === "stuff") {
                d.ctp = "list";
                d.ctl = stuff;
            } else if (d.sn === "ngson") {
                d.ctp = "list";
                d.ctl = ng;
            }

            ret.push(d);
        });

        return ret;
    };

    if (umd.isFin("edit")) {
        return <HandView umd={umd} title={title} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    const hImport = (val) => {
        if (is_empty(col)) {
            alert(loc("l_686"));
            return;
        }

        if (is_empty(val)) {
            alert(loc("l_276"));
            return;
        }

        trim_data(val, ["sn"]);

        umd.update(`file/modify/${mod}`, {v: val});
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 170, frozen: true, formatter: props => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(pact, d, "back")} disabled={no_acc(acc) || d.state === "rej"}>{loc("l_767")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(null, d, "edit")} disabled={no_acc(acc)}>{loc("l_235")}</BtTxt>
                        <BtTxt hcmd={() => hDel(d)} disabled={no_acc(acc)}>{loc("l_237")}</BtTxt>
                    </div>
                );
            }},
        ];

        get_col(col, tmp, map_supply, map_stuff, map_ng);

        return tmp;
    };

    const getList = () => {
        if (is_empty(col)) {
            return null;
        }

        return col.map(d => d.sn);
    };

    const rowTempl = () => {
        const tmp = getList();
        if (is_empty(tmp)) {
            return null;
        }

        const v = {};
        tmp.forEach(k => v[k] = "1");

        return [v];
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn className="mr-4" hcmd={() => umd.pact(null, null, "col")} disabled={no_acc(acc)}>{loc("l_221")}</Btn>
            <KFile umd={umd} title={title} col={getList()} row={rowTempl()} hcmd={hImport} no_acc_in={no_acc(acc)}/>
        </div>
    );

    const Left = () => <Title mod={title} sub={loc("l_831")}/>;

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Right/>} hcmd={v => umd.setFilter(v)}/>
            <GridTable col={getCol()} row={getRow} high={high}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_859")}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {BaseView};
